package com.flute.haflute.alarm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.flute.haflute.agent.topo.Node;
import com.flute.haflute.monitor.JobMonitorInfo;
import com.flute.haflute.monitor.MessageTransfer;
import com.flute.haflute.monitor.StatusMessage;

public class AlarmService {
	private static Logger logger = LoggerFactory.getLogger(AlarmService.class);
	
	static AlarmService alarmSvr;
	List<Node> list = new ArrayList<Node>();

	public static AlarmService getInstance() {

		if (alarmSvr == null) {
			alarmSvr = new AlarmService();
		}
		return alarmSvr;
	}

	public void reportLostNode(Node node) {
		list.add(node);
		StatusMessage status = new StatusMessage();
		status.topic = "节点告警-移除";
		status.content = "节点: " + node.getIp() + " 被移除";
		sendMsg(node.getIp(), status);
	}

	public void reportAddNewNode(Node node) {

		if (list.contains(node)) {
			StatusMessage status = new StatusMessage();
			status.topic = "节点告警-恢复";
			status.content = "节点: " + node.getIp() + " 恢复";
			sendMsg(node.getIp(), status);
		}
	}

	public void reportFinishendJob(JobMonitorInfo reportNode) {
		try {
			StatusMessage status = new StatusMessage();
			reportNode.getMaster().getIp();
			String content = "";
			if (reportNode != null
					&& !reportNode.getJobDescription().equals("")) {
				content = "</br> 作业描述 :"
						+ reportNode.getJobDescription()
						+ "</br> 监控内容:"
						+ (reportNode.getStatusMessage() == null ? ""
								: reportNode.getStatusMessage().content);
			}
			status.content = content;
			status.topic = "任务完成消息通知";
			status.isFinish = true;
			sendMsg(reportNode.getMaster().getIp(), status);
			status = null;
		} catch (Exception e) {
			logger.error(" reportFinishendJob error :" + e);
		}

	}

	private void sendMsg(String ip, StatusMessage status) {
		Map<String, StatusMessage> map = new HashMap<String, StatusMessage>();
		map.put(ip + "^" + status.topic, status);
		MessageTransfer.clusterMsgSend("receiveStatusMessage", map);
		String content = "节点IP:" + ip + " </br> 汇报主题：" + status.topic
				+ status.content;
		try {
			MailService.getInstance().sendMail(content);
		} catch (Exception e) {
			logger.error(" sendMsg " + e);

		}
	}

}
